package com.lanou.renrenxin.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.adapter.ChattingAdapter;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.dao.ChatList;
import com.lanou.renrenxin.onclicklistener.LimitTimeListener;
import com.lanou.renrenxin.onclicklistener.OnChattingItemClickListener;
import com.lanou.renrenxin.singleton.RenrenxinSingleton;
import com.lanou.renrenxin.tools.FormatTime;
import com.lanou.renrenxin.tools.RecorderVoice;
import com.lanou.renrenxin.tools.SendMessage;
import com.lanou.renrenxin.tools.StringValues;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by zouhui on 16/3/3.
 */
public class ChattingActivity extends BaseActivity implements View.OnClickListener, OnChattingItemClickListener, View.OnTouchListener, TextWatcher, LimitTimeListener {
    private static final int REQUEST_IMAGE = 2;
    private String username;
    private String mUsername;
    private ImageButton backBtn, userBtn, voiceOrText, moreBtn,
            addImageBtn, addVideoBtn, addlocationBtn, addFileBtn;
    private RecyclerView recyclerView;
    private EditText messageBody;
    private Button sendBtn, sendVoice;
    private LinearLayout linearLayout;
    private TextView usernameTv;
    private ChattingAdapter adapter;
    private BroadcastReceiver deliveryAckMessageReceiver;
    private LinearLayoutManager linearLayoutManager;
    private NewMessageBroadcastReceiver msgReceiver;
    private ChattingAdapter.ChattingSendViewHolder holder;
    private int count = 0;//记录点击语音或文本按钮的次数
    private int moreCount = 0;//记录更多点击次数
    private Handler handler;
    private RecorderVoice recorderVoice;
    private String isSend = "";
    private RelativeLayout.LayoutParams layoutParams;
    private ArrayList<String> mSelectPath;
    private ChattingAdapter.ChattingSendImageViewHolder sendImageViewHolder;
    private SendMessage sendMessage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatting);
        //只有注册了广播才能接收到新消息，目前离线消息，在线消息都是走接收消息的广播（离线消息目前无法监听，在登录以后，接收消息广播会执行一次拿到所有的离线消息）
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter =
                new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(4);
        registerReceiver(msgReceiver, intentFilter);
        registerBroadCast();
        findId();
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 105) {
                    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                }
                if (msg.what == 106) {
                    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                }
                if (msg.what == 230) {
                    sendImageViewHolder = (ChattingAdapter.ChattingSendImageViewHolder) msg.obj;
                }
                if (msg.what == 222) {
                    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                    sendImageViewHolder.imageView.setProgress((Integer) msg.obj);
                    if ((Integer) msg.obj == 100) {
                        sendImageViewHolder.imageView.setProgress(101);
                    }


                }
                return false;
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(msgReceiver);
    }



    private void registerBroadCast() {
        EMChatManager.getInstance().getChatOptions().setRequireDeliveryAck(false);
        //如果用到已发送的回执需要把这个flag设置成true
        IntentFilter deliveryAckMessageIntentFilter =
                new IntentFilter(EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction());
        deliveryAckMessageIntentFilter.setPriority(5);
        registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter);

        /**
         * 消息送达BroadcastReceiver
         */
        deliveryAckMessageReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                abortBroadcast();

                String msgid = intent.getStringExtra("msgid");
                String from = intent.getStringExtra("from");
                EMConversation conversation = EMChatManager.getInstance().getConversation(from);
                if (conversation != null) {
                    // 把message设为已读
                    EMMessage msg = conversation.getMessage(msgid);
                    if (msg != null) {
                        msg.isDelivered = true;
                    }
                }
            }
        };
    }


    /**
     * 加载控件
     */
    private void findId() {
        Intent intent = getIntent();
        username = intent.getStringExtra("USER_NAME");
        mUsername = intent.getStringExtra("M_USER_NAME");

        recorderVoice = new RecorderVoice();

        linearLayout = (LinearLayout) findViewById(R.id.ll_activity_chatting);
        userBtn = (ImageButton) findViewById(R.id.iv_activity_chatting_user);
        usernameTv = (TextView) findViewById(R.id.tv_activity_chatting_username);
        recyclerView = (RecyclerView) findViewById(R.id.recycle_activity_chatting);
        messageBody = (EditText) findViewById(R.id.editText_activity_chatting_body);
        voiceOrText = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_voiceortext);
        moreBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_send_more);
        sendVoice = (Button) findViewById(R.id.btn_activity_chatting_sendvoice);
        sendBtn = (Button) findViewById(R.id.btn_activity_chatting_send);
        addImageBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_add_Image);
        addVideoBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_add_video);
        addlocationBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_add_file);
        addFileBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_add_file);
        backBtn = (ImageButton) findViewById(R.id.imgBtn_activity_chatting_back);

        addImageBtn.setOnClickListener(this);
        addFileBtn.setOnClickListener(this);
        addlocationBtn.setOnClickListener(this);
        addVideoBtn.setOnClickListener(this);
        usernameTv.setText(username);
        messageBody.addTextChangedListener(this);
        sendBtn.setOnClickListener(this);
        sendVoice.setOnTouchListener(this);
        moreBtn.setOnClickListener(this);
        voiceOrText.setOnClickListener(this);
        userBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        recorderVoice.setLimitTimeListener(this);

        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new ChattingAdapter(this, username, mUsername);
        adapter.setOnChattingItemClickListener(this);
        recyclerView.setAdapter(adapter);
        sendMessage = new SendMessage(adapter, handler, recyclerView);
        recyclerView.scrollToPosition(adapter.getItemCount() - 1);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imgBtn_activity_chatting_back:
                finish();
                break;
            case R.id.btn_activity_chatting_send:
                // TODO: 16/3/3 发送消息
                sendMessage.sendTextMessage(content(), mUsername, username, obtainTime());
                recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                moreBtn.setVisibility(View.VISIBLE);
                sendBtn.setVisibility(View.GONE);
                Toast.makeText(this, "发送文本成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_activity_chatting_user:
                // TODO: 16/3/3 好友信息
                Intent intent = new Intent(this, PIMActivity.class);
                intent.putExtra("PIM_USER_NAME", username);
                startActivity(intent);
                break;
            case R.id.imgBtn_activity_chatting_send_more:
                // TODO: 16/3/5 更多
                changeSelectWindow(70);
                break;
            case R.id.imgBtn_activity_chatting_voiceortext:
                if (count % 2 == 0) {
                    messageBody.setVisibility(View.GONE);
                    sendVoice.setVisibility(View.VISIBLE);
                    voiceOrText.setImageResource(R.mipmap.voice);
                    count++;
                } else {
                    messageBody.setVisibility(View.VISIBLE);
                    sendVoice.setVisibility(View.GONE);
                    voiceOrText.setImageResource(R.mipmap.text);
                    count++;
                }
                break;
            case R.id.imgBtn_activity_chatting_add_Image:
                // TODO: 16/3/8 发送图片
                selectImage();
                break;
            case R.id.imgBtn_activity_chatting_add_video:
                // TODO: 16/3/8 发送视频
                break;
            case R.id.imgBtn_activity_chatting_add_location:
                // TODO: 16/3/8 发送定位
                break;
            case R.id.imgBtn_activity_chatting_add_file:
                // TODO: 16/3/8 发送文件
                break;
        }
    }

    private void selectImage() {
        mSelectPath = new ArrayList<>();
        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        boolean showCamera = true;
        int maxNum = 9;
        Intent intent = new Intent(ChattingActivity.this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, showCamera);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择

        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }


    private void changeSelectWindow(int height) {
        layoutParams = (RelativeLayout.LayoutParams) linearLayout.getLayoutParams();
        layoutParams.height = height;
        layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
        linearLayout.setLayoutParams(layoutParams);
    }


    private String obtainTime() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//24小时制
        String time = sdformat.format(calendar.getTime());
        return time;
    }

    private String content() {
        String content = messageBody.getText().toString();
        messageBody.setText("");
        if (content.equals("")) return null;
        return content;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SendMessage resultSendMessage = new SendMessage(adapter, handler, recyclerView);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (int i = 0; i < mSelectPath.size(); i++) {
                    resultSendMessage.sendImage(mSelectPath.get(i), mUsername, username, obtainTime());
                }
            }
        }
    }

    /**
     * 头像点击事件
     *
     * @param username
     */
    @Override
    public void onHeadImgClick(String username) {
        Intent intent = new Intent(this, PIMActivity.class);
        intent.putExtra("PIM_USER_NAME", mUsername);
        intent.putExtra("detail", username);
        startActivity(intent);
    }

    /**
     * 聊天记录长按事件处理
     *
     * @param username
     */
    @Override
    public void onChattingItemLongClick(String username) {
        showMyDialog();
    }

    /**
     * 播放语音
     *
     * @param path
     */
    @Override
    public void playVoice(String path) {
        recorderVoice.playVoice(path);
    }

    @Override
    public void ItemClick() {
        changeSelectWindow(0);
    }

    /**
     * 显示消息处理对话框
     */
    private void showMyDialog() {

    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                recorderVoice.recorderVoice();
                break;
            case MotionEvent.ACTION_UP:
                if (!isSend.equals(recorderVoice.getPaths())) {
                    recorderVoice.stopRecorder();
                    sendMessage.sendVoice(recorderVoice.getPaths(),
                            recorderVoice.getLen(),mUsername,username,recorderVoice,isSend);
                }
                break;
        }
        return false;
    }


    /**
     * EditText 文本变化以前
     *
     * @param s
     * @param start
     * @param count
     * @param after
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        moreBtn.setVisibility(View.VISIBLE);
        sendBtn.setVisibility(View.GONE);
    }

    /**
     * EditText 文本变化时
     *
     * @param s
     * @param start
     * @param before
     * @param count
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        moreBtn.setVisibility(View.GONE);
        sendBtn.setVisibility(View.VISIBLE);
        if (messageBody.getText().toString().equals("")) {
            changeSelectWindow(0);
            moreBtn.setVisibility(View.VISIBLE);
            sendBtn.setVisibility(View.GONE);

        }
    }

    /**
     * EditText 文本变化后
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 限时发送自动发送语音
     */
    @Override
    public void limitTime() {
        sendMessage.sendVoice(recorderVoice.getPaths(), recorderVoice.getLen(),mUsername,username,recorderVoice,isSend);
        Toast.makeText(this, "最多可以\r\n录制60秒", Toast.LENGTH_SHORT).show();


    }

    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 截断广播
            abortBroadcast();

            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            ChatList chat = new ChatList();
            String body = "";
            String msgType = "";
            if (message.getType() == EMMessage.Type.TXT) {
                msgType = StringValues.MSG_TYPE_TXT;
                body = ((TextMessageBody) message.getBody()).getMessage();
            } else if (message.getType() == EMMessage.Type.FILE) {
                msgType = StringValues.MSG_TYPE_FILE;
            } else if (message.getType() == EMMessage.Type.IMAGE) {
                msgType = StringValues.MSG_TYPE_IMAGE;
                body = ((ImageMessageBody) message.getBody()).getRemoteUrl();
            } else if (message.getType() == EMMessage.Type.LOCATION) {
                msgType = StringValues.MSG_TYPE_LOCATION;
            } else if (message.getType() == EMMessage.Type.VOICE) {
                msgType = StringValues.MSG_TYPE_VOICE;
                body = ((VoiceMessageBody) message.getBody()).getLocalUrl();
            } else if (message.getType() == EMMessage.Type.VIDEO) {
                msgType = StringValues.MSG_TYPE_VIDEO;
            }
            chat.setBody(body);
            chat.setMsg_type(msgType);
            chat.setUsername(message.getUserName());
            chat.setMUsername(mUsername);
            adapter.notifyReceiveMsg(chat);
            recyclerView.scrollToPosition(adapter.getItemCount() - 1);
            RenrenxinSingleton.getInstence().saveChatList(mUsername, username, body,
                    FormatTime.formatTime(message.getMsgTime()), 2, 0, msgType);
            // 如果是群聊消息，获取到group id
            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(username)) {
                // 消息不是发给当前会话，return
                return;
            }
        }
    }

}
